<!--
 * @Author: mengqingchen mengqingchen@huaru.cc
 * @Date: 2022-06-03 13:13:50
 * @LastEditors: mengqingchen mengqc1995@163.com
 * @LastEditTime: 2023-03-07 15:39:47
 * @FilePath: \sososn-web-new\src\App.vue
 * @Description: 
-->
<template>
  <el-config-provider :locale="locale">
    <el-scrollbar ref="scrollRef" :always="true" @scroll="scrollProxy">
      <router-view />
    </el-scrollbar>
  </el-config-provider>
  <!-- 右侧悬浮   -->
  <popup-box @to-top="toTop" />
</template>

<script>
import { onMounted, onUnmounted } from 'vue'

import { useRoute, useRouter } from 'vue-router'

import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import PopupBox from './components/popupBox.vue'
import AOS from 'aos'

export default {
  name: 'App',
  components: { 'popup-box': PopupBox },
  setup() {
    onMounted(() => {
      if (import.meta.env.MODE === 'production') {
        window.addEventListener('resize', () => Refresh())
      }
    })

    const router = new useRouter()
    function Refresh() {
      router.go(0)
    }
    onUnmounted(() => {
      if (import.meta.env.MODE === 'production') {
        window.removeEventListener('resize', Refresh())
      }
    })

    const scrollRef = ref(null)

    const cubic = value => Math.pow(value, 3)
    const easeInOutCubic = value =>
      value < 0.5 ? cubic(value * 2) / 2 : 1 - cubic((1 - value) * 2) / 2
    function toTop() {
      // el-scrollbar 容器
      const el = scrollRef.value.wrapRef

      const beginTime = Date.now()
      const beginValue = el.scrollTop
      const rAF = window.requestAnimationFrame || (func => setTimeout(func, 16))
      const frameFunc = () => {
        const progress = (Date.now() - beginTime) / 500
        if (progress < 1) {
          el.scrollTop = beginValue * (1 - easeInOutCubic(progress))
          rAF(frameFunc)
        } else {
          el.scrollTop = 0
        }
      }
      rAF(frameFunc)
    }
    //在el-scrollbar的监听它自己的scroll事件调用这个方法（@scroll=“scrollProxy”）
    const scrollProxy = scrollParams => {
      window.pageYOffset = scrollParams.scrollTop
      window.scrollY = scrollParams.scrollTop
      AOS.refresh()
    }
    /* 切换路由，回到顶部 */
    const route = useRoute()
    watch(
      () => {
        return route.path
      },
      () => {
        scrollRef.value.setScrollTop(0)
        window.pageYOffset = 0
        window.scrollY = 0
        AOS.refresh()
      }
    )

    return {
      scrollRef,
      toTop,
      locale: zhCn,
      scrollProxy
    }
  }
}
</script>

<style lang="scss">
#app {
  width: 100%;
  height: 100vh;
  font-family: Avenir, Helvetica, Arial, sans-serif, 'Microsoft YaHei';
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background: #f8f8f9;
}
</style>
